import math
import re
from datetime import datetime

def extract_by_template(template: str, text: str):
    text = text.strip()
    template = template.strip()
    # 将模板中 {key} 替换为正则命名组 (?P<key>.+?)
    def replacer(match):
        key = match.group(1)
        return rf'(?P<{key}>.+?)'  # 非贪婪匹配，防止吞掉后面的内容
    # 转义模板中的其他字符
    pattern = re.escape(template)
    # 替换 {变量} 为正则命名捕获组
    pattern = re.sub(r'\\{(\w+)\\}', replacer, pattern)

    # 用 fullmatch 确保整段文本匹配模板
    match = re.fullmatch(pattern, text)
    
    if match:
        result = match.groupdict()
        if 'time' in result:
            time_str = result['time']
            dt = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S.%f")
            timestamp = dt.timestamp()
            result['time'] = timestamp
        return result
    else:
        return None

if __name__ == "__main__":
    # template = "{timestamp} Speed= {speed} km/h Location: {location}"
    template = "{time} DEBUG GetServoState id: 1, v {v}, angle {angle}, size: 2, A: {current1} {current2}"
    text = "2025-07-22 09:20:15.153 DEBUG GetServoState id: 1, v 0.000000, angle -0.003781, size: 2, A: 1.000000 -1.000000"

    result = extract_by_template(template, text)
    print(result)
    
    # template = ""
    # text = "SpeedSpeed= 45.3 km/h Location: 120.33E,31.23N"

    result = extract_by_template(template, text)
    print(result)
